package com.ry.est.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.ry.est.constants.Constants;
import com.ry.est.entity.Users;
import com.ry.est.service.TokenService;
import com.ry.est.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public TokenVo generateToken(Users users) {
        TokenVo tokenVo = new TokenVo();
        //生成token
        String uuid = UUID.fastUUID().toString(true);
        tokenVo.setToken(uuid);
        //保存会话信息
        saveToken(uuid,users);
        return tokenVo;
    }

    @Override
    public void saveToken(String token, Users users) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String usersJsonString = JSON.toJSONString(users);
        operations.set(Constants.Redis.PREFIX_TOKEN +token,usersJsonString,60, TimeUnit.MINUTES);
    }

    @Override
    public Users getUserInfoByToken(String token) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        String s = operations.get(Constants.Redis.PREFIX_TOKEN + token);

        if (null == s){
            return null;
        }else{
            Users users = JSON.parseObject(s, Users.class);

            return users;
        }

    }

    @Override
    public void removeToken(String token) {
        redisTemplate.delete(token);
    }
}
